{{Extend "layout"}}

{{Block "title"}}{{Stored.data.Host}} - {{"文件管理"|T}}{{/Block}}
{{Block "breadcrumb"}}
{{Super}}
<li><a href="__BACKEND__/term/account">{{"SSH"|T}}</a></li>
<li>{{Stored.data.Name}} <span style="color:grey">({{Stored.data.Username}}@{{Stored.data.Host}})</span></li>
<li class="active">
    <a href="__BACKEND__/term/sftp?id={{Form "id"}}"><span class="badge badge-primary">sftp:</span> </a>
    {{/* Stored.Get "path" */}}
    {{- range $k,$v := Stored.pathLinks -}}
    /<a href="{{$v.V}}">{{$v.K}}</a>
    {{- end -}}
</li>
{{/Block}}

{{Block "head"}}
<link rel="stylesheet" href="__ASSETS__/js/dropzone/min/dropzone.min.css" />
<!-- codemirror -->
<link rel="stylesheet" href="__ASSETS__/js/codemirror/lib/codemirror.min.css">
<link rel="stylesheet" href="__ASSETS__/js/codemirror/addon/display/fullscreen.css">
<link rel="stylesheet" href="__ASSETS__/js/codemirror/theme/night.css">
<script src="__ASSETS__/js/codemirror/lib/codemirror.min.js"></script>
<script src="__ASSETS__/js/codemirror/addon/mode/loadmode.js"></script>
<script src="__ASSETS__/js/codemirror/mode/meta.js"></script>
<script src="__ASSETS__/js/codemirror/addon/display/fullscreen.js"></script>
{{/Block}}

{{Block "main"}}
{{$id := Form "id"}}
{{$path := Stored.Get "path"}}
{{$parentPath := Stored.Get "parentPath"}}
{{$pathPrefix := Stored.Get "pathPrefix"}}
<div class="row">
	<div class="col-md-12">
		<div class="block-flat">
			<div class="header">
				<div class="btn-group">
					<button type="button" id="uploadBtn" class="btn btn-primary" title="{{"上传文件到当前目录"|T}}" data-toggle="tooltip">
                        <i class="fa fa-upload"></i>
                        {{"上传文件"|T}}
                    </button>
					<button type="button" id="mkdirBtn" class="btn btn-success" title="{{"在当前目录下新建文件夹"|T}}" data-toggle="tooltip" data-url="__BACKEND__/term/sftp?id={{$id}}&do=mkdir&path={{$pathPrefix}}" onclick="fileRename(this,null,true)">
                        <i class="fa fa-plus"></i>
                        {{"新建文件夹"|T}}
                    </button>
                    <span class="input-group" style="padding-left:10px">
                        <input type="text" id="query-current-path" name="query" class="form-control typeahead" required="required" value="{{Form "query"}}" data-provide="typeahead">
                        <span class="input-group-btn"><button class="btn btn-default" type="button" id="btn-query-current-path"><i class="fa fa-search"></i></button></span>
                    </span>
				</div>
			</div>
			<div class="content">
				<div class="table-responsive">
				<table class="table no-border hover">
					<thead class="no-border">
						<tr>
							<th><strong>{{"名称"|T}}</strong></th>
							<th style="width:15%;"><strong>{{"修改日期"|T}}</strong></th>
							<th style="width:15%;"><strong>{{"类型"|T}}</strong></th>
							<th style="width:15%;"><strong>{{"大小"|T}}</strong></th>
							<th style="width:15%;"><strong>{{"权限"|T}}</strong></th>
							<th style="width:120px" class="text-center"><strong>{{"操作"|T}}</strong></th>
						</tr>
					</thead>
					<tbody class="no-border-y" id="tbody-content">
                        <tr>
							<td>
                                <i class="fa fa-folder-o"></i>
                                <a title="{{"点击回到上一级"|T}}" href="__BACKEND__/term/sftp?id={{$id}}&path={{$parentPath}}" style="font-size:18px;font-weight:bold" data-toggle="tooltip">..</a>
                            </td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
						</tr>
                        {{range $k,$v := Stored.dirs}}
                        {{$mode := $v.Mode.String}}
						<tr item='{{$v.Name}}'>
							<td>
                                {{if $v.IsDir}}
                                <i class="fa fa-folder-o"></i>
                                {{else}}
                                <i class="fa fa-file-o"></i>
                                {{end}}
                                <a href="__BACKEND__/term/sftp?id={{$id}}&path={{$pathPrefix}}{{$v.Name}}">{{$v.Name}}</a>
                                &nbsp;
                                <a href="javascript:;" title="{{"重命名"|T}}" data-url="__BACKEND__/term/sftp?id={{$id}}&do=rename&path={{$pathPrefix}}{{$v.Name}}" onclick="fileRename(this,'{{$v.Name}}',{{if $v.IsDir}}true{{else}}false{{end}})" data-toggle="tooltip">
                                <i class="fa fa-pencil"></i>
                                </a>
                            </td>
							<td>{{$v.ModTime.Format "2006-01-02 15:04:05"}}</td>
							<td>
                                {{if $v.IsDir}}
                                {{"文件夹"|T}}
                                {{else if HasPrefix $mode "L"}}
                                {{"链接"|T}}
                                {{else}}
                                {{"文件"|T}}
                                {{end}}
                            </td>
							<td>{{if $v.IsDir}}-{{else}}{{$v.Size|FormatByte}}{{end}}</td>
							<td>{{$mode}}</td>
							<td>
                                <a title="{{"删除"|T}}" class="label label-danger" href="__BACKEND__/term/sftp?id={{$id}}&do=delete&path={{$pathPrefix}}{{$v.Name}}" onclick="return confirm('{{T "真的要删除“%v”吗？" $v.Name}}');" data-toggle="tooltip">
                                <i class="fa fa-times"></i>
                                </a>
                                {{if not $v.IsDir}}
                                &nbsp;
                                <a title="{{"下载"|T}}" class="label label-info" href="__BACKEND__/term/sftp?id={{$id}}&path={{$pathPrefix}}{{$v.Name}}" data-toggle="tooltip">
                                <i class="fa fa-cloud-download"></i>
                                </a>
                                {{end}}
                                {{if and (not $v.IsDir) (Editable $v.Name)}}
                                &nbsp;
                                <a title="{{"编辑"|T}}" class="label label-success" href="javascript:;" data-url="__BACKEND__/term/sftp?id={{$id}}&do=edit&path={{$pathPrefix}}{{$v.Name}}" onclick="fileEdit(this,'{{$v.Name}}')" data-toggle="tooltip">
                                <i class="fa fa-pencil"></i>
                                </a>
                                {{end}}
                            </td>
						</tr>
                        {{end}}
					</tbody>
				</table>		
				</div>
			</div>
		</div>				
	</div>
</div>
 
{{Modal "__TMPL__/caddy/file.yaml"}}
{{Modal "__TMPL__/caddy/file_zip.yaml"}}
{{Modal "__TMPL__/caddy/file_rename.yaml"}}
{{Modal "__TMPL__/caddy/file_edit.yaml"}}
{{/Block}}

{{Block "footer"}}
{{$id := Form "id"}}
<script type="text/javascript" src="__ASSETS__/js/dropzone/min/dropzone.min.js"></script>
<script type="text/javascript">
function uploadURL(currentPath){
    return BACKEND_URL+'/term/sftp?id={{$id}}&do=upload&path='+encodeURIComponent(currentPath);
}
function refreshList() {
    App.loading('show');
    $.get(window.location.href,{'_pjax':'tbody-content'},function(r){
        var e=$(r);
        $('#tbody-content').html(e.find('#tbody-content').html());
        App.loading('hide');
    },'html');
}
var dropzone;
function initDropzone() {
    $('#multi-upload-dropzone').dropzone({
        url:uploadURL('{{Stored.path}}'),
        dictDefaultMessage:'{{"可以把文件拖到这里来进行上传哦"|T}}'
    });
    dropzone=$('#multi-upload-dropzone').get(0).dropzone;
}
function initCodeMirrorEditor() {
    editor = CodeMirror.fromTextArea($("#file-edit-content")[0], {
      lineNumbers: true,
      theme: "night",
      extraKeys: {
        "F11": function(cm) {
          cm.setOption("fullScreen", !cm.getOption("fullScreen"));
        },
        "Esc": function(cm) {
          if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
        }
      }
    });
    editor.setOption('lineWrapping', true);
    editor.setSize('auto', 'auto');
    $('#file-edit-modal .modal-footer .btn-success').on('click',function(){
        var url=$(this).data('url');
        var enc=$('#use-encoding-open').val();
        if(!enc)enc='';
        $.post(url,{content:editor.getValue(),encoding:enc},function(r){
            if(r.Code!=1)return App.message({title: '{{"系统消息"|T}}', text: r.Info,class_name:'error'},false);
            return App.message({title: '{{"系统消息"|T}}', text: '{{"保存成功"|T}}',class_name:'success'},false);
        },'json');
    });
    $('#file-edit-modal .modal-body').css('padding',0);
    $('#use-encoding-open').on('change',function(){
        var enc=$(this).val();
        fileReopen(enc);
    });
    
}

function fileReopen(encoding,url) {
    App.loading('show');
    if(url==null)url=$('#file-edit-modal .modal-footer .btn-success').data('url');
    $.get(url,{encoding:encoding},function(r){
        App.loading('hide');
        if(r.Code!=1)return App.message({title: '{{"系统消息"|T}}', text: r.Info,class_name:'error'},false);
        editor.setValue(r.Data);
    },'json');
}

function fileEdit(obj,file) {
    var url=$(obj).data('url');
    $('#file-edit-modal .modal-footer .btn-success').data('url',url);
    App.loading('show');
    $.get(url,{},function(r){
        App.loading('hide');
        if(r.Code!=1)return App.message({title: '{{"系统消息"|T}}', text: r.Info,class_name:'error'},false);
        $('#file-edit-modal .modal-header h3').html('{{"编辑文件"|T}}: '+file);
        $('#file-edit-modal').niftyModal('show',{
            afterOpen: function(modal) {
                editor.setValue(r.Data);
                codeMirrorChangeMode(editor,file);
            },
            afterClose: function(modal) {
                $('#use-encoding-open').find('option:selected').prop('selected',false);
            }
        });
    },'json');
}
var langModifyDirName='{{"修改文件夹名"|T}}', langModifyFileName='{{"修改文件名"|T}}',
langMkdirName='{{"新建文件夹"|T}}';
function fileRename(obj,file,isDir) {
    var url=$(obj).data('url');
    $('#file-rename-modal .modal-footer .btn-primary:last').data('url',url);
    var headTitle=file==null?langMkdirName:(isDir ? langModifyDirName : langModifyFileName)+': '+file;
    $('#file-rename-modal .modal-header h3').html(headTitle);
    $('#file-rename-modal').niftyModal('show',{afterOpen:function(modal){
        if(file!=null) $('#file-rename-input').val(file);
    }});
}
function codeMirrorChangeMode(editor,val) {
  var m, mode, spec;
  if (m = /.+\.([^.]+)$/.exec(val)) {
    var info = CodeMirror.findModeByExtension(m[1]);
    if (info) {
      mode = info.mode;
      spec = info.mime;
    }
  } else if (/\//.test(val)) {
    var info = CodeMirror.findModeByMIME(val);
    if (info) {
      mode = info.mode;
      spec = val;
    }
  } else {
    mode = spec = val;
  }
  if (mode) {
    editor.setOption("mode", spec);
    CodeMirror.autoLoadMode(editor, mode);
  } else {
    console.log("Could not find a mode corresponding to " + val);
  }
}
Dropzone.autoDiscover=false;
CodeMirror.modeURL = "__ASSETS__/js/codemirror/mode/%N/%N.js";

function init(){
    initDropzone();
    initCodeMirrorEditor();
	$('#uploadBtn').off().on('click',function(event){
		$('#multi-upload-modal').niftyModal('show',{afterClose:function(modal){
            dropzone.removeAllFiles();
            refreshList();
        }});
	});
    $(window).off().on('resize',function(){
        $('#file-edit-modal').css({height:$(window).height(),width:'100%','max-width':'100%',left:0,top:0,transform:'none'});
        $('#file-edit-form').css({height:$(window).height()-150,width:'100%','max-width':'100%',overflow:'auto'});
    });
    $(window).trigger('resize');
    $('#file-rename-modal .modal-footer .btn-primary:last').off().on('click',function(){
        var url=$(this).data('url');
        App.loading('show');
        $.post(url,{name:$('#file-rename-input').val()},function(r){
            App.loading('hide');
            if(r.Code!=1)return App.message({title: '{{"系统消息"|T}}', text: r.Info, class_name: 'error'},false);
            App.message({title: '{{"系统消息"|T}}', text: r.Info, class_name: 'success'},false);
            refreshList();
        },'json');
    });
}
{{if Form "_pjax"}}
init();
{{else}}
$(init);
{{end}}
$(function(){
    $('#query-current-path').on('keyup',function(event){
        var q=$(this).val();
        if(q==''){
            $('#tbody-content').children('tr:not(:visible)').show();
            return;
        }
        $('#tbody-content').children('tr:not([item*="'+q+'"])').hide();
        $('#tbody-content').children('tr[item*="'+q+'"]:not(:visible)').show();
        if(event.keyCode==13){
            var tr=$('#tbody-content').children('tr:visible');
            if(tr.length==1){
                var a=tr.children('td:first').children('a:first');
                var url=a.attr('href');
                window.location=url;
                return;
            }
        }
    }).focus();
    $('#btn-query-current-path').on('click',function(){
        $('#query-current-path').trigger('keyup');
    });
    //App.searchFS('#query-current-path',20,'',BACKEND_URL+'/term/sftp?id={{$id}}&do=search&path={{Stored.Get "pathPrefix"}}');
});
</script>
{{/Block}}